package com.autohammal.implement;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import com.autohammal.ITarget;
import com.autohammal.task.Task;

public class FileMoveTask extends Task {

	private static final long serialVersionUID = -3599344014665978829L;

	public FileMoveTask() {
	}

	public FileMoveTask(ITarget target) {
		super(target);
	}

	@Override
	public void executeTask() {

		String srcfile = (String) getTarget().getConfigurationItem("targetDir");
		String desfile = (String) getTarget().getConfigurationItem("desfile");

		File srcf = new File(srcfile);
		// if(!srcf.exists())return;
		File desf = new File(desfile);
		if (!desf.exists()) {
			if (desf.isFile()) {
				File dir = desf.getParentFile();
				if (!dir.exists())
					dir.mkdirs();
				try {
					desf.createNewFile();
				} catch (IOException e) {
					Logger.getLogger(getClass()).log(Level.ERROR, e);
				}
			} else {
				desf.mkdirs();
				desf = new File(desf, srcf.getName());
				if (!desf.exists()) {
					try {
						desf.createNewFile();
					} catch (IOException e) {
						Logger.getLogger(getClass()).log(Level.ERROR, e);
					}
				}
			}
		} else {
			desf = new File(desf, srcf.getName());
			if (desf.exists()) {
				int nameEnd = desf.getName().lastIndexOf(".");
				String beforName = desf.getName().substring(0, nameEnd);
				String endName = desf.getName().substring(nameEnd);
				desf = new File(desf.getParentFile(), beforName
						+ System.currentTimeMillis() + endName);
			}
			try {
				if (desf != null)
					desf.createNewFile();
			} catch (IOException e) {
				Logger.getLogger(getClass()).log(Level.ERROR, e);
			}
		}

		try {
			OutputStream out = new FileOutputStream(desf);
			BufferedInputStream bin = new BufferedInputStream(
					new FileInputStream(srcf));
			byte[] data = new byte[1024 * 5];
			int len = -1;
			while ((len = bin.read(data)) != -1) {
				out.write(data, 0, len);
			}
			out.flush();
			out.close();
			bin.close();
		} catch (FileNotFoundException e) {
			Logger.getLogger(getClass()).log(Level.ERROR, e);
		} catch (IOException e) {
			Logger.getLogger(getClass()).log(Level.ERROR, e);
		}

		if (srcf != null && srcf.exists()) {
			srcf.delete();
		}

	}

}
